from odoo import fields, models, api, _
from odoo.exceptions import AccessError
from odoo.tools import float_compare


class StockPicking(models.Model):
    _inherit = 'stock.picking'

    is_visible_panel_qty = fields.Boolean(string='visible panel qty', compute='_compute_is_invisible_panel_qty', store=True, readonly=True, copy=False, default=False)
    s_material_order = fields.Boolean(string='Is material order', default=False, copy=False)  # 投料向导创建的领料单，标记字段
    s_material_share = fields.Boolean(string='Is material share', default=False, copy=False)  # 投料向导创建的领料单，标记字段, 是否已分摊

    is_autocomplete = fields.Boolean(default=False, compute="_compute_is_autocomplete", store=True)

    s_mrp_production_ids = fields.Many2many('mrp.production', 's_mrp_production_stock_picking_rel')

    @api.depends('products_availability_state', 'state')
    def _compute_is_autocomplete(self):
        for rec in self:
            if rec.state == 'assigned' and rec.origin and rec.picking_type_id.barcode and rec.picking_type_id.barcode == 'WTT-PC':
                validate = True
                for move in rec.move_ids:
                    if float_compare(move.product_qty, move.quantity, precision_rounding=move.product_uom.rounding) == 1:
                        validate = False

                if validate:
                    rec.sudo().button_validate()
                    rec.is_autocomplete = True

    @api.depends('location_dest_id')
    def _compute_is_invisible_panel_qty(self):
        for rec in self:
            if rec.location_dest_id.barcode and rec.location_dest_id.barcode == 'WH-PREPRODUCTION':
                rec.is_visible_panel_qty = True
            else:
                rec.is_visible_panel_qty = False

    def action_cancel(self):
        if self:
            if not any([self.env.is_admin(), self.env.is_superuser(), self.env.user.has_group('pcbmanufact.group_stock_cancel_manager')]):
                raise AccessError(_('You do not have permission to cancel the stock order!'))
        return super().action_cancel()

    def button_validate(self):
        if self:
            if not any([self.env.is_admin(), self.env.is_superuser(), self.env.user.has_group('pcbmanufact.group_stock_confirm_manager')]):
                raise AccessError(_('You do not have permission to validate the stock order!'))
        return super().button_validate()
